﻿using System.Collections.Generic;

namespace HCore
{
    public class MessageDispatcher
    {
        private EntityManager _entityMgr;
        private PrecisionTimer _timer;

        public MessageDispatcher(EntityManager e, PrecisionTimer t)
        {
            _entityMgr = e;
            _timer = t;
        }

        private readonly List<Telegram> _priorityQ = new List<Telegram>();

        void Discharge(BaseGameEntity receiver, Telegram msg)
        {
            if (!receiver.HandleMessage(msg))
            {
                Logger.Log("Message not handled");
            }
        }

        internal void DispatchMsg(Fix delay, int sender, int receiver, int msgType, object extraInfo = null)
        {
            BaseGameEntity rEntity = _entityMgr.GetEntityFromID(receiver);

            Debug.Assert(rEntity != null, string.Format("receiver Entity: {0} == null", sender));

            Telegram telegram = new Telegram(0, sender, receiver, msgType, extraInfo);

            if (delay <= Fix.Zero)
            {
                Discharge(rEntity, telegram);
            }
            else
            {
                Fix currentTime = _timer.currentTime;
                telegram.dispatchTime = currentTime + delay;
                _priorityQ.Add(telegram);
            }
        }

        internal void DispatchDelayedMessages()
        {
            Fix currentTime = _timer.currentTime;

            for (int i = _priorityQ.Count - 1; i >= 0; i--)
            {
                Telegram t = _priorityQ[i];
                if (t.dispatchTime < currentTime && t.dispatchTime > 0)
                {
                    BaseGameEntity receiver = _entityMgr.GetEntityFromID(t.receiver);

                    Discharge(receiver, t);
                    _priorityQ.RemoveAt(i);
                }
            }
        }

        internal void Reset()
        {
            _priorityQ.Clear();
        }
    }
}